package com.empire.devops.emops.es.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.empire.devops.emops.common.BaseResponse;
import com.empire.devops.emops.es.entity.OpsProjectEntity;
import com.empire.devops.emops.es.service.IOpsProjectService;
import com.empire.devops.emops.es.vo.AppItemVO;
import com.empire.devops.emops.es.vo.OpsProjectDetailVO;
import com.empire.devops.emops.es.vo.OpsProjectQueryVO;
import com.empire.devops.emops.es.vo.OpsProjectVO;
import com.empire.devops.emops.utils.PageResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Es数据搜素接口功能
 *
 * @author aaron
 * @date 2021/9/5
 */
@Api(tags = "用户项目API")
@ApiSort(2)
@RestController
@RequestMapping("/userProject")
@Slf4j
public class UserProjectController {
    private final IOpsProjectService opsProjectService;

    @Autowired
    public UserProjectController(IOpsProjectService opsProjectService) {
        this.opsProjectService = opsProjectService;
    }

    @ApiOperation(value = "获取APP项下拉接口", notes = "APP项下拉")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "/getAppItem", method = {RequestMethod.GET}, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<List<AppItemVO>> getAppItem() {
        List<AppItemVO> data = Lists.newArrayList();
        List<OpsProjectEntity> opsProjectList = opsProjectService.list();
        opsProjectList.forEach(item -> {
            data.add(AppItemVO.newInstance(item));
        });
        BaseResponse rs = BaseResponse.success(data);
        return rs;
    }

    @ApiOperation(value = "新增日志项目接口", notes = "新增日志项目接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "addOpsProject", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    public BaseResponse addOpsProject(@RequestBody OpsProjectVO opsProjectVO) {
        log.info("调用addOpsProject();param:{}", JSON.toJSONString(opsProjectVO));
        try {
            OpsProjectEntity opsProjectEntity = opsProjectVO.toOpsProjectEntity();
            Date now = new Date();
            opsProjectEntity.setCreateTime(now);
            opsProjectService.save(opsProjectEntity);
        } catch (Exception e) {
            log.error("addOpsProject()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success();
    }

    @ApiOperation(value = "更新日志项目接口", notes = "更新日志项目接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "updateOpsProject", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    public BaseResponse updateOpsProject(@RequestBody OpsProjectVO opsProjectVO) {
        log.info("updateOpsProject();param:{}", JSON.toJSONString(opsProjectVO));
        try {
            OpsProjectEntity opsProjectEntity = opsProjectVO.toOpsProjectEntity();
            Date now = new Date();
            opsProjectEntity.setUpdateTime(now);
            opsProjectService.updateById(opsProjectEntity);
        } catch (Exception e) {
            log.error("updateOpsProject()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success();
    }

    @ApiOperation(value = "查询日志项目列表接口", notes = "查询日志项目列表接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "queryPage", method = {RequestMethod.POST}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = {"application/json; charset=UTF-8"})
    public BaseResponse<PageResult<OpsProjectDetailVO>> queryPage(@RequestBody OpsProjectQueryVO opsProjectQueryVO) {
        log.info("queryPage();param:{}", JSON.toJSONString(opsProjectQueryVO));
        try {
            LambdaQueryWrapper<OpsProjectEntity> opsProjectWrapper = Wrappers.lambdaQuery();
            if (StringUtils.isNotBlank(opsProjectQueryVO.getAppName())) {
                opsProjectWrapper.like(OpsProjectEntity::getAppName, opsProjectQueryVO.getAppName());
            }
            if (StringUtils.isNotBlank(opsProjectQueryVO.getName())) {
                opsProjectWrapper.like(OpsProjectEntity::getName, opsProjectQueryVO.getName());
            }
            if (opsProjectQueryVO.getExpired() != null) {
                opsProjectWrapper.eq(OpsProjectEntity::getExpired, opsProjectQueryVO.getExpired());
            }
            if (StringUtils.isNotBlank(opsProjectQueryVO.getRemark())) {
                opsProjectWrapper.like(OpsProjectEntity::getRemark, opsProjectQueryVO.getRemark());
            }
            if (StringUtils.isNotBlank(opsProjectQueryVO.getIpAddress())) {
                opsProjectWrapper.like(OpsProjectEntity::getIpAddress, opsProjectQueryVO.getIpAddress());
            }
            PageResult<OpsProjectDetailVO> pageResult = new PageResult<>();
            // 两个参数：current的值默认是1，从1开始，不是0。size是每一页的条数。
            Page<OpsProjectEntity> page = new Page<>(opsProjectQueryVO.getPage(), opsProjectQueryVO.getPageSize());
            Page<OpsProjectEntity> opsProjectPage = opsProjectService.page(page, opsProjectWrapper);
            List<OpsProjectDetailVO> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(opsProjectPage.getRecords())) {
                opsProjectPage.getRecords().forEach(item -> {
                    list.add(OpsProjectDetailVO.newInstance(item));
                });
            }
            pageResult.setList(list);
            pageResult.setCount(((Long) opsProjectPage.getTotal()).intValue());
            return BaseResponse.success(pageResult);
        } catch (Exception e) {
            log.error("queryPage()", e);
            return BaseResponse.fail("系统繁忙");
        }

    }


    @ApiOperation(value = "删除日志项目接口", notes = "删除日志项目接口")
    @ApiOperationSupport(order = 1)
    @RequestMapping(value = "/deleteOpsProject/{id}", method = {RequestMethod.DELETE}, produces = {"application/json; charset=UTF-8"})
    public BaseResponse deleteOpsProject(@PathVariable("id") Integer id) {
        log.info("deleteOpsProject();param:{}", id);
        try {
            opsProjectService.removeById(id);
        } catch (Exception e) {
            log.error("deleteOpsProject()", e);
            return BaseResponse.fail("系统繁忙");
        }
        return BaseResponse.success();
    }
}
